import { AfterViewChecked, Component, ElementRef, EventEmitter, Injector, Output, ViewChild, ViewEncapsulation } from '@angular/core';
import { AppConsts } from '@shared/AppConsts';
import { AppComponentBase } from '@shared/common/app-component-base';
import { OrganizationUnitDto, ProfileServiceProxy, OutsourcingTaskDto, TaskServiceProxy, OutsourcingWorkflowServiceProxy, UserServiceProxy, OutsourcingDto, OutsourcingWorkflowStepUserDto, OutsourcingWorkflowInputDto, OutsourcingFormInputDto, SupplierServiceProxy, OutsourcingServiceProxy } from '@shared/service-proxies/service-proxies';
import { ModalDirective } from 'ngx-bootstrap';
import { IOrganizationUnitsTreeComponentData, OrganizationUnitsTreeComponent } from '../shared/organization-unit-tree.component';
import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';
import { TaskService } from '../task/Task.service';

import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { Paginator } from 'primeng/components/paginator/paginator';
import { Table } from 'primeng/components/table/table';
import { SelectItem, SelectItemGroup } from 'primeng/api';
@Component({
    selector: 'flowapplyCrucialCreate',
    templateUrl: './flowapplyCrucialCreate.component.html',
    styleUrls: ['./flowapplyCrucialCreate.component.css']
})
export class FlowapplyCrucialCreateComponent extends AppComponentBase {
    @ViewChild('createOrEditModal') modal: ModalDirective;
    @ViewChild('paginator') paginator: Paginator;
    @ViewChild('taskdataTable') taskdataTable: Table;
    @ViewChild('dataTable') dataTable: Table;


    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();
    filterText = '';
    active = false;
    saving = false;
    selectedCar3: string;
    task: OutsourcingTaskDto = new OutsourcingTaskDto();
    Outsourcings;
    supplierUnits = [];
    SupplierAyy: SelectItem[];
    users: SelectItem[];
    stepusers: OutsourcingWorkflowStepUserDto;
    workflow: OutsourcingWorkflowInputDto = new OutsourcingWorkflowInputDto();
    clonedOutsourcings: { [s: number]: OutsourcingDto; } = {};

    taskType = 0;
    isReceived = undefined;
    isCompleted = false;

    constructor(injector: Injector,
        private _taskServiceProxy: TaskServiceProxy,
        private _outSourcingworkflowServiceProxy: OutsourcingWorkflowServiceProxy,
        private _taskService: TaskService,
        private _supplierService: SupplierServiceProxy,
        private _outSourcingServiceProxy: OutsourcingServiceProxy,
        private _userService: UserServiceProxy,
        private _profileService: ProfileServiceProxy) {
        super(injector);
    }

    show(taskId?: number): void {
        this.Outsourcings = [];
        this.workflow = new OutsourcingWorkflowInputDto();
        this._supplierService.getAllSupplierItems().subscribe(resultdata => {
            this.SupplierAyy = resultdata;
        });
        this._userService.getAllUserForDropDown2().subscribe(resultdata => {
            console.log(resultdata);
            this.users = resultdata;
        });

        this.active = true;
        this._taskService.clearOutSourcs();
        this._outSourcingworkflowServiceProxy.buildWorkFlowCode().subscribe(flowcode => {
            this.workflow.code = flowcode;
            this.modal.show();
        });
    }
    // tslint:disable-next-line: use-life-cycle-interface
    ngOnInit(): void {


        this.stepusers = new OutsourcingWorkflowStepUserDto();
    }
    onShown(): void {
        //document.getElementById('Code').focus();
    }

    joinTask(data) {
        let outsourcing = this.Outsourcings.filter(x => x.taskForModelId === data.id)[0];

        if (outsourcing === undefined) {
            console.log(outsourcing);
            console.log(data);
            let _dto = new OutsourcingDto();
            _dto.taskForModelId = data.id;
            _dto.picNo = data.drawingCode;
            _dto.taskCode = data.taskCode;
            _dto.taskName = data.drawingName;
            _dto.taskCount = data.totalQuantity;
            _dto.outsourcingAmount = 0;
            _dto.deliveryRate = null;
            _dto.workStatus = '';
            _dto.unitPrice = 0;
            this.Outsourcings.push(_dto);
        } else {
            this.notify.info('该任务已经在申请列表中！');
        }
    }

    save(): void {
        let input = new OutsourcingFormInputDto();
        input.outSourcingDtos = this.Outsourcings;
        input.workflowDto = this.workflow;
        input.workflowDto.supplierUnit = this.supplierUnits.toString();
        input.stepUserDto = this.stepusers;
        this.saving = true;
        //判断审批用户是否设置
        console.log(this.stepusers);
        if (!this.stepusers.workshopManager||this.stepusers.workshopManager==='-1') {
            this.notify.info('请选择单位经办人');
            this.saving = false;
            return;
        }
        if (!this.stepusers.workShopLeader||this.stepusers.workShopLeader==='-1') {
            this.notify.info('请选择单位主管领导');
            this.saving = false;
            return;
        }
        if (!this.stepusers.plannedProductionModelManager||this.stepusers.plannedProductionModelManager==='-1') {
            this.notify.info('计划生产处型号主管');
            this.saving = false;
            return;
        }
        if (!this.stepusers.plannedProductionLeader||this.stepusers.plannedProductionLeader==='-1') {
            this.notify.info('计划生产处主管处长');
            this.saving = false;
            return;
        }

        if (!this.stepusers.qualityDepartmentLeader||this.stepusers.qualityDepartmentLeader==='-1') {
            this.notify.info('质量处主管处长');
            this.saving = false;
            return;
        }
        if (!this.stepusers.technicalManager||this.stepusers.technicalManager==='-1') {
            this.notify.info('工艺处主管处长');
            this.saving = false;
            return;
        }
        if (!this.stepusers.plannedProductionDirector||this.stepusers.plannedProductionDirector==='-1') {
            this.notify.info('计划生产处处长');
            this.saving = false;
            return;
        }
        if (!this.stepusers.chiefEngineer||this.stepusers.chiefEngineer==='-1') {
            this.notify.info('副总指挥(副总工程师)');
            this.saving = false;
            return;
        }
        if (!this.stepusers.customerRepresentative||this.stepusers.customerRepresentative==='-1') {
            this.notify.info('顾客代表');
            this.saving = false;
            return;
        }
        if (!this.stepusers.companyLeader||this.stepusers.companyLeader==='-1') {
            this.notify.info('公司领导');
            this.saving = false;
            return;
        }
        console.log(input);
        this._outSourcingworkflowServiceProxy.createOrUpdateCrucialWorkFlow(input)
            .pipe(finalize(() => { this.saving = false; }))
            .subscribe(() => {
                this.notify.info(this.l('SavedSuccessfully'));
                this.close();
                this.modalSave.emit(null);
            });
    }
    onRowEditInit(task: OutsourcingDto) {
        console.log(task);
        this.clonedOutsourcings[task.taskForModelId.toString()] = { ...task };
    }
    onRowEditSave(task: OutsourcingDto) {
        if (task.outsourcingAmount > 0) {
            delete this.clonedOutsourcings[task.taskForModelId.toString()];
            this.notify.info(this.l('SavedSuccessfully'));
        } else {
            this.notify.info('申请数量不能小于0');
        }
    }
    onRowEditCancel(task: OutsourcingDto, index: number) {
        console.log(this.clonedOutsourcings[task.taskForModelId.toString()]);
        this.Outsourcings[index] = this.clonedOutsourcings[task.taskForModelId.toString()];
        delete this.Outsourcings[task.taskForModelId];
    }
    close(): void {
        this.active = false;
        this.modal.hide();
    }

    getTasks(event?: LazyLoadEvent) {
        if (this.primengTableHelper.shouldResetPaging(event)) {
            this.paginator.changePage(0);
            return;
        }
        this.primengTableHelper.showLoadingIndicator();
        this._taskServiceProxy.getTaskForModel(
            this.taskType,
            this.filterText,
            this.isReceived,
            undefined,
            this.isCompleted,
            0,
            this.primengTableHelper.getSkipCount(this.paginator, event),
            this.primengTableHelper.getMaxResultCount(this.paginator, event)
        ).pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator())).subscribe(result => {
            console.log('4444');
            this.primengTableHelper.totalRecordsCount = result.totalCount;
            this.primengTableHelper.records = result.items;
            this.primengTableHelper.hideLoadingIndicator();
        });
    }

    getOutsourcing(event?: LazyLoadEvent) {
        this.Outsourcings = this._taskService.getOutSourcings();
    }
    deleteRow(task: OutsourcingDto): void {
        let index = this.Outsourcings.indexOf(task);
        this.Outsourcings.splice(index, 1);
    }
}
